
"""角色视图函数模块"""
import datetime

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from common.http_util import Result
from system.system_models import RolePermission, Role

'''进入角色界面'''
def to_role(request):
    return render(request, "page/system/sys_role.html")

from common.db_util import MySqlDb

'''角色列表数据，api接口'''
class RoleList(APIView):
    def get(self, request):
        # 获取查询参数
        params = request.GET.dict()
        print("params:",params)
        where_clause = ""
        #用户名称
        role_name = params.get("role_name")
        if role_name:
            where_clause += f" and role_name like '%{role_name}%'"
        #状态信息
        status = params.get("status")
        if status:
            status = int(status)
            if status == -1:
                where_clause += " and status in (0,1)"
            else:
                where_clause += " and status = :status"
        #查询数据库，用户列表数据
        sql = "select * from sys_role where 1=1 "
        #拼接sql
        if where_clause:
            sql += where_clause
        role_list= MySqlDb.query(sql,params)
        #把数据返回到前端
        return Response(Result(data=role_list))


def iterate_tree(menu_tree,array:list):
    for item in menu_tree:
        if item.get("children"):
            iterate_tree(item["children"],array)
        else:
            #菜单+叶子节点
            if (item.get("is_leaf") or item.get("menu_type")==2) and item.get("checked"):
                array.append(item["id"])
'''新增角色'''
class RoleAdd(APIView):
    def post(self, request):
        session = None
        try:
            # 获取请求参数
            params = request.data
            print("params:",params)
            # 取出menu_tree
            menu_tree = params.get("menu_tree")
            menu_ids = []
            if menu_tree:
                iterate_tree(menu_tree,menu_ids)

            session = MySqlDb.get_mysql_session()
            # 开始事务
            session.begin()

            # 创建角色
            role = Role(
                role_name=params.get("role_name"),
                role_key=params.get("role_key"),
                sort=params.get("sort"),
                status=params.get("status"),
                remark=params.get("remark"),
                is_deleted=params.get("is_deleted"),
                create_time=datetime.datetime.now(),
                update_time=datetime.datetime.now()
            )
            session.add(role)
            session.flush()  # 刷新以获取ID

            # 插入角色菜单关系
            if menu_ids:
                for menu_id in menu_ids:
                    role_menu = RolePermission(
                        role_id=role.id,
                        menu_id=menu_id
                    )
                    session.add(role_menu)

            session.commit()
            return Response(Result(data=1))

        except Exception as e:
            print(e)
            if session:
                session.rollback()
            return Response(Result(code=444,msg="新增失败！==>"+str(e),data=0))
        finally:
            if session:
                session.close()


'''角色信息修改'''
class RoleModify(APIView):
    def post(self, request):
        print("=========== 进入到了RoleModify ==========")
        # 获取请求参数
        params = request.data
        print("params:",params)
        role:Role = Role()
        #取出前端传来的参数：role_id,role_name,role_key,sort,status,description,is_deleted,create_time,update_time
        role.id = params.get("id")
        menu_ids = params.get("menu_ids")     # 取出menu_tree
        menu_tree = params.get("menu_tree")
        menu_ids = []
        if menu_tree:
           iterate_tree(menu_tree,menu_ids)

        session = MySqlDb.get_mysql_session()
        try:
            #查询出用户信息
            role:Role = session.query(Role).filter(Role.id==params.get("id")).first()
            if role:
                #更新用户信息
                role.role_name = params.get("role_name")
                role.role_key = params.get("role_key")
                role.sort = params.get("sort")
                role.status = params.get("status")
                role.remark = params.get("remark")
                role.is_deleted = params.get("is_deleted")
                role.update_time = datetime.datetime.now()
                session.commit()

                #删除角色菜单关系
                sql = "delete from sys_role_permission where role_id=:role_id"
                MySqlDb.delete(sql,params={"role_id":role.id})
                #插入角色菜单关系
                if menu_ids:
                    for menu_id in menu_ids:
                        role_menu = RolePermission(
                            role_id=role.id,
                            menu_id=menu_id
                        )
                        session.add(role_menu)
                        session.commit()

                return Response(Result(data=1))
        except Exception as e:
            print(e)
            session.rollback()
            return Response(Result(code=444,msg="更新失败！==>"+e.__str__(),data=0))
        finally:
            if session:
                session.close()

'''删除角色'''
class RoleDelete(APIView):
    def get(self, request):
        # 获取请求参数
        params = request.GET.dict()
        print("params:",params)
        id = params.get("id")
        #sql删除，物理删除
        sql = "delete from sys_role where id = :id"
        result = MySqlDb.delete(sql,params)
        # 删除角色菜单关系
        sql = "delete from sys_role_permission where role_id=:role_id"
        MySqlDb.delete(sql, params={"role_id": id})
        #删除角色用户关系
        sql = "delete from sys_user_role where role_id=:role_id"
        MySqlDb.delete(sql, params={"role_id": id})
        if result:
            return Response(Result(data=1))
        else:
            return Response(Result(code=444,msg="删除失败！",data=0))

'''批量删除用户'''
class RoleDeleteBatch(APIView):
    def post(self, request):
        # 获取请求参数
        params = request.data
        print("params:",params)
        ids = params.get("ids")
        ids_str = ""
        for id in ids:
            ids_str += f"{id},"
        #去掉最后一个逗号
        ids_str = ids_str[:-1]
        params = {
            "ids":ids_str
        }
        #sql删除，物理删除
        sql = "delete from sys_role where id in (:ids)"
        result = MySqlDb.delete(sql,params)
        # 删除角色菜单关系
        sql = "delete from sys_role_permission where role_id in(:ids)"
        MySqlDb.delete(sql, params={"role_id": ids})
        if result:
            return Response(Result(data=1))
        else:
            return Response(Result(code=444,msg="删除失败！",data=0))

'''查询角色授权限树'''
class RoleSelectTree(APIView):
    def get(self, request):
        print("=========== 进入到了RoleSelectTree ==========")
        # 获取请求参数
        params = request.GET.dict()
        print("params:",params)
        role_id = params.get("role_id")
        role_menu_dict = {}
        if role_id:
            #查询出角色对应的菜单ID
            sql = "select menu_id from sys_role_permission where role_id = :role_id"
            role_menu_list = MySqlDb.query(sql,params)
            for item in role_menu_list:
                role_menu_dict[item["menu_id"]] = item["menu_id"]


        #先查询出子系统
        sql = "select * from sys_sub_system where status=1 order by sort asc"
        system_list = MySqlDb.query(sql,params)
        #查询子系统对应的菜单
        my_systems=[]
        for system in system_list:
            params = {
                "system_id":system["id"]
            }
            sql = "select * from sys_menu where status=1 and system_id =:system_id order by sort asc"
            menu_list = MySqlDb.query(sql,params)
            #组装菜单树
            temp_dict={}
            for menu in menu_list:
                id = menu["id"]
                temp_dict[id]=menu
                menu["label"] = menu["menu_name"]
                menu["expanded"] = False
                #如果菜单id在角色菜单字典中，说明角色有该菜单权限
                if role_menu_dict.get(id):
                    menu["checked"] = True
                else:
                    menu["checked"] = False
            #组装菜单
            menu_tree = []
            for menu in menu_list:
                #如果父菜单ID为0，说明是根菜单
                if menu["parent_id"] == 0:
                    menu_tree.append(menu)
                else:
                    #如果父菜单ID不为0，说明是子菜单
                    parent_menu = temp_dict[menu["parent_id"]]
                    #子菜单不存在时，创建一个空列表
                    if "children" not in parent_menu:
                        parent_menu["children"] = []
                    #把子菜单添加到父菜单的children列表中
                    parent_menu["children"].append(menu)

            #子系统对应的菜单树
            my_systems.append({
                "id":system["id"],
                "label":system["sub_short_name"],
                "expanded":True,
                "system_name":system["system_name"],
                "children":menu_tree
            })
        return Response(Result(data=my_systems))